package com.tangtang.gulimall.product.service.impl;

import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.tangtang.gulimall.product.dao.CategoryBrandRelationDao;
import com.tangtang.gulimall.product.entity.CategoryBrandRelationEntity;
import org.springframework.stereotype.Service;
import java.util.Map;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.tangtang.common.utils.PageUtils;
import com.tangtang.common.utils.Query;

import com.tangtang.gulimall.product.dao.BrandDao;
import com.tangtang.gulimall.product.entity.BrandEntity;
import com.tangtang.gulimall.product.service.BrandService;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;


@Service("brandService")
public class BrandServiceImpl extends ServiceImpl<BrandDao, BrandEntity> implements BrandService {

    //调用中间表进行修改
    @Resource
    private CategoryBrandRelationDao categoryBrandRelationDao;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        //做当前得搜索功能(获取当前搜索得字符串)
        String key = (String) params.get("key");

        QueryWrapper<BrandEntity> queryWrapper =  new QueryWrapper<BrandEntity>();
        if (StringUtils.isEmpty(key)){
            IPage<BrandEntity> page = this.page(
                    new Query<BrandEntity>().getPage(params),
                    queryWrapper
            );
            return new PageUtils(page);
        }else {
            //根据名称进行模糊查询
            queryWrapper.eq("brand_id",key).or().like("name",key);
            IPage<BrandEntity> page = this.page(
                    new Query<BrandEntity>().getPage(params),
                    queryWrapper
            );
            return new PageUtils(page);
        }
    }

    /**
     * 修改中间表以及中间表和中间表绑定的表
     * @param brandEntity
     */
    @Override
    public void saveall(BrandEntity brandEntity) {
        this.updateById(brandEntity);
        //获取修改信息
        Long brandid = brandEntity.getBrandId();
        String brandname = brandEntity.getName();

        //这一块用的是mybatisplus来处理更新。当然可以选择自己喜欢的更新方式，如ibatis（mybatis）的
        UpdateWrapper<CategoryBrandRelationEntity> queryWrapper = new UpdateWrapper<CategoryBrandRelationEntity>();
        queryWrapper.eq("brand_id",brandid);
        //queryWrapper.eq("name",brandname);
        CategoryBrandRelationEntity categoryBrandRelationEntity = new CategoryBrandRelationEntity();
        categoryBrandRelationEntity.setBrandId(brandid);
        categoryBrandRelationEntity.setBrandName(brandname);
        categoryBrandRelationDao.update(categoryBrandRelationEntity,queryWrapper);
    }
}